<template>
  <el-card class="m-demo" shadow="hover" :body-style="{ padding: '20px 20px 0' }">
    <component :is="component"></component>
    <el-divider></el-divider>
    <div ref="code-wrap" class="code-wrap" :style="{ height: height + 'px' }">
      <!-- <p>{{ description }}</p> -->
      <slot></slot>
    </div>
    <div class="operates" :class="{ sticky: expand }">
      <el-divider v-if="expand"></el-divider>
      <el-button type="text" :icon="icon" @click="onToggle">{{ text }}</el-button>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'MDemo',
  props: {
    info: String,
    render: String,
    script: String
  },
  data() {
    return {
      description: decodeURI(this.info),
      component: null,
      expand: false,
      height: 0
    }
  },
  computed: {
    text() {
      return this.expand ? '收起' : '展开'
    },

    icon() {
      return this.expand ? 'el-icon-caret-top' : 'el-icon-caret-bottom'
    }
  },
  watch: {},
  created() {
    const component = new Function(`return ${decodeURI(this.script)}`)()
    component.render = new Function(`return ${decodeURI(this.render)}`)()
    this.component = component
  },
  methods: {
    onToggle() {
      this.expand = !this.expand
      this.height = this.expand ? this.$refs['code-wrap'].scrollHeight : 0
    }
  }
}
</script>

<style lang="scss" scoped>
.m-demo {
  overflow: initial;
  .code-wrap {
    height: 0;
    overflow: hidden;
    transition: height 0.3s;
  }
  .operates {
    &.sticky {
      position: sticky;
      bottom: 0;
      z-index: 1;
    }
    text-align: center;
    background-color: #fff;
  }
  .el-divider {
    margin: 10px -20px;
    width: auto;
  }
}
</style>
